package org.example.spring_security_demo1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.spring_security_demo1.entity.SysMenu;
import org.example.spring_security_demo1.entity.SysUser;
import org.example.spring_security_demo1.mapper.SysMenuMapper;
import org.example.spring_security_demo1.mapper.SysRoleMapper;
import org.example.spring_security_demo1.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }

        List<SysMenu> sysMenus = sysMenuMapper.selectMenuByUserId((long) sysUser.getUserId());
        List<SimpleGrantedAuthority> collect = sysMenus.stream().map((m) -> m.getCode())
                .map((s)->{
                    return new SimpleGrantedAuthority(s);
                })
                .collect(Collectors.toList());
        sysUser.setAuthorities(collect);

        return sysUser;
    }
}
